package com.bayleaf.core;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import net.sf.json.JSONSerializer;

public class Model extends HttpServletRequestWrapper{
	
	public Model(HttpServletRequest req) {
		super(req);
	}
	
	public String getString(String name){
		System.out.println(name);
		return getParameter(name);
	}
	
	public String[] getStrings(String name){
		System.out.println(name);
		return getParameterValues(name);
	}
	
	public void setString(String name, String value){
		setAttribute(name, value);
	}
	
	//TODO:AbstractVO로 변경
	public void setObject(String name, Object vo){
		setAttribute(name, vo);
	}
	
	/**
	 * Model의 데이터를 JSON string으로 바꿈
	 * @return jsonString
	 */
	public String toJson(){
		String result = JSONSerializer.toJSON(toMap()).toString(0);
		System.out.println("Returning JSON : " +result);
		return result;
	}
	
	private Map<String, Object> toMap(){
		Map<String,Object> attrMap = new HashMap<String, Object>();
		Enumeration<String> attrNames = getAttributeNames();
		String name="";
		while(attrNames.hasMoreElements()){
			name=attrNames.nextElement();
			attrMap.put(name, getAttribute(name));
		}
		return attrMap;
	}
	
}
